<template>
  <div
    :class="prefixCls"
    :style="avatarStyle"
    ref="avatar"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
  >
    <div :class="[prefixCls + '-container']">
      <slot>
        <img
          :src="src"
          v-if="src != '' && imgType"
          @error="handleImgError"
          @load="handleImgLoad"
        />
        <i :class="getIcon" :style="iconStyle" v-else></i>
      </slot>
    </div>
    <div
      :class="prefixCls + '-mask'"
      v-show="isShowMaskCom"
      :style="maskStyle"
      @click="handleMaskClick"
    >
      <slot name="mask">
        <span>{{ maskContent }}</span>
      </slot
      >
    </div>
  </div>
</template>
<script>
import { oneOf } from "utils/index.js";
const prefixCls = "vbestui-avatar";
export default {
  name: "BAvatar",
  props: {
    shape: {
      validator(value) {
        return oneOf(value, ["circle", "square"]);
      },
      default: "circle",
    },
    size: {
      type: String,
      default: "",
    },
    icon: {
      type: String,
      default: "vbestui-iconfont icon-avatar",
    },
    src: {
      type: String,
      default: "",
    },
    mask: {
      type: Boolean,
      default: false,
    },
    maskContent: {
      type: String,
      default: "",
    },
    fontSize: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      prefixCls: prefixCls,
      offsetHeight: 0,
      isShowMask: false,
      imgType: true, //img状态
    };
  },
  computed: {
    avatarStyle() {
      return {
        borderRadius: this.shape == "square" ? "4px" : "",
        width: `${this.size}`,
        height: `${this.size}`,
      };
    },
    iconStyle() {
      return {
        fontSize: !this.imgType
          ? `${this.offsetHeight * 0.6}px`
          : `${this.offsetHeight * 0.8}px`,
      };
    },
    maskStyle() {
      return {
        fontSize: this.fontSize,
      };
    },
    /**计算头像框size */
    getHeight() {
      this.$nextTick().then(() => {
        this.offsetHeight = this.$refs.avatar.offsetHeight;
      });
    },
    /**是否显示遮罩 */
    isShowMaskCom() {
      if (!this.mask) return false;
      return this.isShowMask;
    },
    /**要显示的icon */
    getIcon() {
      let icon = "";
      /**图片加载失败 */
      icon = this.icon;
      if (!this.imgType) {
        icon = "vbestui-iconfont icon-img-error";
      }
      return icon;
    },
  },
  methods: {
    handleMouseEnter() {
      this.isShowMask = true;
    },
    handleMouseLeave() {
      this.isShowMask = false;
    },
    handleMaskClick() {
      this.$emit("clickMask");
    },
    handleImgError() {
      this.imgType = false;
      this.$emit("error");
    },
    handleImgLoad() {
      this.imgType = true;
    },
  },
  mounted() {
    this.getHeight;
  },
};
</script>